<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/auth.php';
require_once '../includes/attendance_manager.php';
require_once '../includes/user.php';

// 检查权限
$auth = getAuth();
$auth->requirePermission('super_admin');

// 获取当前用户信息
$currentUser = $auth->getCurrentUser();

// 初始化数据库和考勤管理器
$database = getDatabaseConnection();
$attendanceManager = new AttendanceManager($database);

// 获取当前年月
$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');
$month = isset($_GET['month']) ? intval($_GET['month']) : date('n');

// 计算上个月和下个月
$prevMonth = $month - 1;
$prevYear = $year;
if ($prevMonth < 1) {
    $prevMonth = 12;
    $prevYear = $year - 1;
}

$nextMonth = $month + 1;
$nextYear = $year;
if ($nextMonth > 12) {
    $nextMonth = 1;
    $nextYear = $year + 1;
}

// 获取当月考勤记录
$startDate = date('Y-m-01', strtotime("$year-$month-01"));
$endDate = date('Y-m-t', strtotime("$year-$month-01"));

$attendanceStats = $attendanceManager->getAttendanceStats($startDate, $endDate);

// 获取当月所有考勤记录
$filters = [
    'start_date' => $startDate,
    'end_date' => $endDate
];
$recordsData = $attendanceManager->getAttendanceRecords(1, 1000, $filters);
$records = $recordsData['records'];

// 按日期分组记录
$recordsByDate = [];
foreach ($records as $record) {
    $date = $record['record_date'];
    if (!isset($recordsByDate[$date])) {
        $recordsByDate[$date] = [];
    }
    $recordsByDate[$date][] = $record;
}

// 生成日历
$firstDay = date('N', strtotime("$year-$month-01")); // 1=周一, 7=周日
$daysInMonth = date('t', strtotime("$year-$month-01"));
$weeks = ceil(($firstDay + $daysInMonth) / 7);

// 状态颜色映射
$statusColors = [
    'normal' => 'bg-success',
    'late' => 'bg-warning',
    'early_leave' => 'bg-danger',
    'absent' => 'bg-secondary',
    'leave' => 'bg-info',
    'business_trip' => 'bg-primary',
    'overtime' => 'bg-dark'
];

$statusLabels = [
    'normal' => '正常',
    'late' => '迟到',
    'early_leave' => '早退',
    'absent' => '缺勤',
    'leave' => '请假',
    'business_trip' => '出差',
    'overtime' => '加班'
];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>日历视图 - 考勤管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .calendar-day {
            border: 1px solid #dee2e6;
            height: 120px;
            padding: 5px;
            position: relative;
        }
        .calendar-day.weekend {
            background-color: #f8f9fa;
        }
        .calendar-day.today {
            background-color: #e7f3ff;
        }
        .calendar-day.other-month {
            background-color: #f8f9fa;
            color: #6c757d;
        }
        .day-number {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .status-badge {
            font-size: 0.7rem;
            padding: 2px 5px;
            margin: 1px;
            display: block;
        }
        .calendar-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <?php include_once '../includes/sidebar.php'; ?>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand navbar-custom mb-4">
            <div class="container-fluid">
                <div class="navbar-nav me-auto">
                    <span class="navbar-text">
                        <i class="fas fa-calendar-alt me-2"></i>考勤日历视图
                    </span>
                </div>
                <div class="navbar-nav">
                    <span class="navbar-text me-3">
                        <i class="fas fa-user me-2"></i>
                        <?php echo htmlspecialchars($currentUser['full_name']); ?>
                    </span>
                    <a href="../user/profile.php" class="nav-link">
                        <i class="fas fa-cog"></i> 个人设置
                    </a>
                </div>
            </div>
        </nav>

        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h3><i class="fas fa-calendar-alt me-2"></i>考勤日历视图</h3>
                <div>
                    <a href="?year=<?php echo $prevYear; ?>&month=<?php echo $prevMonth; ?>" class="btn btn-outline-primary">
                        <i class="fas fa-chevron-left"></i> 上个月
                    </a>
                    <span class="mx-3 h4"><?php echo $year; ?>年<?php echo $month; ?>月</span>
                    <a href="?year=<?php echo $nextYear; ?>&month=<?php echo $nextMonth; ?>" class="btn btn-outline-primary">
                        下个月 <i class="fas fa-chevron-right"></i>
                    </a>
                </div>
            </div>

                    <!-- 月度统计 -->
                    <div class="row mb-4">
                        <div class="col-md-2">
                            <div class="card bg-primary text-white">
                                <div class="card-body text-center">
                                    <h4><?php echo $attendanceStats['total_records']; ?></h4>
                                    <p class="mb-0">总记录数</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card bg-success text-white">
                                <div class="card-body text-center">
                                    <h4><?php echo $attendanceStats['normal_count']; ?></h4>
                                    <p class="mb-0">正常</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card bg-warning text-white">
                                <div class="card-body text-center">
                                    <h4><?php echo $attendanceStats['late_count']; ?></h4>
                                    <p class="mb-0">迟到</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card bg-danger text-white">
                                <div class="card-body text-center">
                                    <h4><?php echo $attendanceStats['early_leave_count']; ?></h4>
                                    <p class="mb-0">早退</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card bg-secondary text-white">
                                <div class="card-body text-center">
                                    <h4><?php echo $attendanceStats['absent_count']; ?></h4>
                                    <p class="mb-0">缺勤</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card bg-info text-white">
                                <div class="card-body text-center">
                                    <h4><?php echo $attendanceStats['leave_count']; ?></h4>
                                    <p class="mb-0">请假</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 日历 -->
                    <div class="card">
                        <div class="card-header calendar-header">
                            <div class="row text-center fw-bold">
                                <div class="col">周一</div>
                                <div class="col">周二</div>
                                <div class="col">周三</div>
                                <div class="col">周四</div>
                                <div class="col">周五</div>
                                <div class="col">周六</div>
                                <div class="col">周日</div>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <?php
                            $dayCounter = 1;
                            $today = date('Y-m-d');
                            
                            for ($week = 0; $week < $weeks; $week++) {
                                echo '<div class="row">';
                                for ($weekday = 1; $weekday <= 7; $weekday++) {
                                    $dayClass = 'calendar-day';
                                    
                                    // 周末样式
                                    if ($weekday >= 6) {
                                        $dayClass .= ' weekend';
                                    }
                                    
                                    // 其他月份的天数
                                    if (($week == 0 && $weekday < $firstDay) || $dayCounter > $daysInMonth) {
                                        echo '<div class="col '.$dayClass.' other-month"></div>';
                                        continue;
                                    }
                                    
                                    $currentDate = sprintf('%04d-%02d-%02d', $year, $month, $dayCounter);
                                    
                                    // 今天样式
                                    if ($currentDate == $today) {
                                        $dayClass .= ' today';
                                    }
                                    
                                    echo '<div class="col '.$dayClass.'">';
                                    echo '<div class="day-number">'.$dayCounter.'</div>';
                                    
                                    // 显示当天的考勤状态
                                    if (isset($recordsByDate[$currentDate])) {
                                        $dayRecords = $recordsByDate[$currentDate];
                                        $statusCounts = [];
                                        
                                        foreach ($dayRecords as $record) {
                                            $status = $record['status'];
                                            if (!isset($statusCounts[$status])) {
                                                $statusCounts[$status] = 0;
                                            }
                                            $statusCounts[$status]++;
                                        }
                                        
                                        foreach ($statusCounts as $status => $count) {
                                            $color = $statusColors[$status] ?? 'bg-dark';
                                            $label = $statusLabels[$status] ?? $status;
                                            echo '<span class="badge '.$color.' status-badge">'.$label.' ('.$count.')</span>';
                                        }
                                    } else {
                                        echo '<small class="text-muted">无记录</small>';
                                    }
                                    
                                    echo '</div>';
                                    $dayCounter++;
                                }
                                echo '</div>';
                            }
                            ?>
                        </div>
                    </div>

                    <!-- 图例 -->
                    <div class="card mt-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0"><i class="fas fa-info-circle me-2"></i>状态图例</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <?php foreach ($statusLabels as $status => $label): ?>
                                    <div class="col-md-3 mb-2">
                                        <span class="badge <?php echo $statusColors[$status]; ?> me-2"><?php echo $label; ?></span>
                                        <small class="text-muted">- <?php echo $status; ?></small>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
